package com.csxy.hxl.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csxy.hxl.entity.EduSubject;
import com.csxy.hxl.entity.excel.SubjectData;
import com.csxy.hxl.exception.MyException;
import com.csxy.hxl.service.EduSubjectService;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    private EduSubjectService eduSubjectService;
    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }
    public SubjectExcelListener() {
    }
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null){
            throw new MyException(20001,"excel文件数据为空");
        }
        EduSubject existOneSubject =this.existOneSubject(eduSubjectService, subjectData.getOneSubjectName()) ;
        if (existOneSubject == null){
        existOneSubject = new EduSubject();
        existOneSubject.setTitle(subjectData.getOneSubjectName());
        eduSubjectService.save(existOneSubject);
        }
        String parent_id = existOneSubject.getId();
         EduSubject existTwoSubject = this.existTwoSubject(eduSubjectService, subjectData.getTwoSubjectName(), parent_id);
         if (existTwoSubject == null){
             existTwoSubject = new EduSubject();
             existTwoSubject.setParentId(parent_id);
             existTwoSubject.setTitle(subjectData.getTwoSubjectName());
             eduSubjectService.save(existTwoSubject);
         }

    }
    private EduSubject existOneSubject(EduSubjectService eduSubjectService, String name) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject oneSubject = eduSubjectService.getOne(wrapper);
        return oneSubject;
    }
    private EduSubject existTwoSubject(EduSubjectService eduSubjectService, String name, String parentId) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",parentId);
        EduSubject twoSubject = eduSubjectService.getOne(wrapper);
        return twoSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
